package tech.wisefin.track.evidence;

import com.alibaba.fastjson.JSON;
import com.baidu.xchain.saas.SaasJavaManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tech.wisefin.track.EvidenceProvider;

import java.io.File;

/**
 * 使用baidu超级链生成可信凭证
 * 只能在Linux平台下使用
 **/
@Slf4j
@Service
public class DefaultEvidenceProvider implements EvidenceProvider {

    @Autowired
    protected BaiduXChainProperties props;

    @Autowired
    protected SaasJavaManager saasJavaManager;

    @Override
    public String provide(File file) {
        String osName = System.getProperty("os.name");
        if (!"Linux".equals(osName)) {
            log.warn("百度超级链仅支持 Linux 环境");
            return "fake-hash";
        }
        if (StringUtils.isEmpty(props.getPassword())) {
            log.warn("请配置password环境变量：值为生成百度超级链账号时设置的密码！");
            return "fake-hash";
        }
        SaasJavaManager.setLibraryPath(props.getLibPath());

        BaiduXChainApiReturnModel pathModel = JSON.parseObject(
                saasJavaManager.isAddressExist(props.getPath()),
                BaiduXChainApiReturnModel.class
        );

        if (!Boolean.parseBoolean(pathModel.getData().toString())) {
            log.warn("private.key 不存在，需要配置 private.key 路径。请参考：https://xchain.baidu.com/n/console#/industrywidget/doc");
            return "fake-hash";
        }

        BaiduXChainApiReturnModel hashModel = JSON.parseObject(
                saasJavaManager.getFileHash(file.getAbsolutePath()),
                BaiduXChainApiReturnModel.class
        );
        if (hashModel.getCode().equals("1")) {
            throw new RuntimeException("百度超级链文件获取hash异常！异常信息：" + hashModel.getMsg());
        }

        // 百度超级链必传参数
        BaiduChainParam chainParam = new BaiduChainParam();
        chainParam.setFileName(file.getName());
        chainParam.setFileHash(hashModel.getData().toString());
        chainParam.setHashAlg("SM3");

        // 进行跨链存证
        BaiduXChainApiReturnModel txIdModel = JSON.parseObject(
                saasJavaManager.crossTransfer(
                        props.getChainName(),
                        JSON.toJSONString(chainParam),
                        props.getPath(),
                        props.getPassword(),
                        props.getHost()
                ), BaiduXChainApiReturnModel.class);

        if (txIdModel.getCode().equals("1")) {
            throw new RuntimeException("百度超级链上链异常！异常信息：" + txIdModel.getMsg());
        }
        return txIdModel.getData().toString();
    }
}
